package com.freeman.cement.controller;

import com.alibaba.fastjson.JSONObject;
import com.freeman.cement.entity.ResponseResult;
import com.freeman.cement.exception.AppException;
import com.freeman.cement.exception.AppExceptionCodeMsg;
import com.freeman.cement.service.EventRecvService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.Console;
import java.io.IOException;
import java.util.*;

/**
 * 事件采集服务
 * 用于直接对接海康平台，通过事件回调机制，接收新报警事件的推送
 */

@Controller
public class EventRecvController {
    @Resource
    private EventRecvService service;

    /**
     * 取得全部事件类型列表
     * springmvc在controller层使用map接收前端传过来的json数据时，必须使用@RequstBody才能自动接收参数不然无法接收参数
     * @param sbody
     */
    @RequestMapping(value = "/eventRecv", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    //如果不加@ResponseBody注解的话，会导致重定向，返回null即可避免重定向
    @ResponseBody
    public void eventRecv(@RequestBody String sbody) {
        System.out.println("------------------------接收到新事件---------------------------------");
        System.out.println("event body:\n" + sbody);
        if (StringUtils.isNotBlank(sbody)) {
            service.eventRecv(sbody);
        }
        System.out.println("------------------------事件解析完毕---------------------------------");
    }

    //springmvc在controller层使用map接收前端传过来的json数据时，必须使用@RequstBody才能自动接收参数不然无法接收参数
    //接收原始报文调试，将接收到的报文存入数据库
    //这种方法非常简单
    @RequestMapping(value = "/eventRecvDebug", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    //如果不加@ResponseBody注解的话，会导致重定向，返回null即可避免重定向
    @ResponseBody
    public void eventRecvDebug(@RequestBody String sbody) {
        System.out.println("---------------------------接收到新事件-------------------------------");
        System.out.println("RequestBody:\n" + sbody);
        service.eventRecord(sbody);
        System.out.println("--------------------------事件报文存储完毕-----------------------------");
    }

    @RequestMapping(value = "/eventRecvTest", method = RequestMethod.POST, produces = "application/json;charset=UTF-8")
    @ResponseBody
    public ResponseResult eventRecvTest(@RequestBody String sbody) {
        System.out.println("---------------------------接收到新事件-------------------------------");
        System.out.println("RequestBody:\n" + sbody);
        if (StringUtils.isNotBlank(sbody)) {
            ResponseResult rslt = service.eventRecvTest(sbody);
            System.out.println("--------------------------事件报文解析完毕-----------------------------");
            return rslt;
        } else {
            throw new AppException(AppExceptionCodeMsg.CONTENT_IS_NULL);
        }
    }

    /*//springmvc在controller层使用map接收前端传过来的json数据时，必须使用@RequstBody才能自动接收参数不然无法接收参数
    public void eventRecv(String method, @RequestParam String params) {
        if (StringUtils.isNotBlank(params)) {
            service.eventRecv(params);
        }
    }*/

    /*//接收原始报文调试，将接收到的报文存入数据库
    //这种方法非常简单
    @RequestMapping(value = "/eventRecvDebug", method = RequestMethod.POST, produces = "application/json")
    public void eventRecvDebug(@RequestBody String sbody) {
        System.out.println("----------------------------------------------------------");
        System.out.println(sbody);
        System.out.println("----------------------------------------------------------");
        service.eventRecord(sbody);
    }*/

    //使用下面的方法也可以接收到报文
    //接收原始报文调试，将接收到的报文存入数据库
    /*@RequestMapping(value = "/eventRecvDebug", method = RequestMethod.POST, produces = "application/json")
    public void eventRecvDebug(HttpServletRequest request) {
        //获取参数map
        //获取不到无用
        *//*Map<String, String> map = new HashMap<>();
        Enumeration<String> paramNames = request.getParameterNames();
        while (paramNames.hasMoreElements()) {
            String paramName = paramNames.nextElement();
            String[] paramValues = request.getParameterValues(paramName);
            if (paramValues.length == 1) {
                String paramValue = paramValues[0];
                if (paramValue.length() != 0) {
                    map.put(paramName, paramValue);
                }
            }
        }
        //打印参数map
        System.out.println("----------------------------------------------------------");
        map.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });*//*

        System.out.println("----------------------------------------------------------");
        //获取request报文
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try {
            br = request.getReader();
            String _str;
            while ((_str = br.readLine()) != null) {
                sb.append(_str);
            }
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != br) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            //打印request报文
            System.out.println("request:" + sb.toString());
            System.out.println("----------------------------------------------------------");
            //存储request报文
            service.eventRecord(sb.toString());
        }
    }*/


}

    /*if (StringUtils.isNotBlank(method) && method.equals("OnEventNotify") && StringUtils.isNotBlank(params)) {
        service.eventRecv(params);
    }*/

    /*public void eventRecv(EventBase eventBase){
        if(eventBase.getMethod().equals("OnEventNotify") && eventBase.getParams() != null && !eventBase.getParams().equals("")){
            service.eventRecv(eventBase.getParams());
        }
    }*/

    //@RequestMapping(value = "/eventRecv", method = RequestMethod.POST, produces = "text/plain;charset=utf-8")
    //@ResponseBody
    /*public void eventRecvDebug(HttpServletRequest request) {
        Map map = request.getParameterMap();

        BufferedReader br = null;
        StringBuilder sb = new StringBuilder("");
        try
        {
            br = request.getReader();
            String _str;
            while ((_str = br.readLine()) != null)
            {
                sb.append(_str);
            }
            br.close();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != br)
            {
                try
                {
                    br.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
        System.out.println("----------------------------------------------------------");
        System.out.println("request:" + sb.toString());
        System.out.println("ContextPath:" + request.getContextPath());
        System.out.println("getContentLength:" + request.getContentLength());
        System.out.println(map.toString());
        System.out.println(map.size());
        map.forEach((key, value) -> {
            System.out.println(key + ":" + value);
        });
        System.out.println("----------------------------------------------------------");

        String str = "";
        Set keSet = map.entrySet();
        for (Iterator itr = keSet.iterator(); itr.hasNext(); ) {
            Map.Entry me = (Map.Entry) itr.next();
            Object ok = me.getKey();
            Object ov = me.getValue();
            String[] value = new String[1];
            if (ov instanceof String[]) {
                value = (String[]) ov;
            } else {
                value[0] = ov.toString();
            }

            for (int k = 0; k < value.length; k++) {
                System.out.println(ok + "=" + value[k]);
                str += (ok + "=" + value[k] + "\n");
            }

        }
        service.eventRecord(str);
    }*/

